﻿using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace TinyUpdater
{
	public class Updater
	{
		public void DownloadPatch(string path)
		{
			
		}

		public void RunPatcher(IEnumerable<PatchFile> patchFiles)
		{
			ExtractBsPatch();
			foreach (PatchFile patchFile in patchFiles)
			{
				string oldFilePath;
				string newFilePath;
				RunBsPatch(oldFilePath, newFilePath, patchFile.FilePath);
			}
		}

		private string RunBsPatch(string oldFile, string newFile, string patchFile)
		{
			Process bspatch = Process.Start(
				new ProcessStartInfo("bspatch.exe")
					{
						CreateNoWindow = true, 
						UseShellExecute = false, 
						RedirectStandardOutput = true, 
						RedirectStandardError = true, 
						Arguments = string.Format("{0} {1} {2}", oldFile, newFile, patchFile)
					});

			bspatch.WaitForExit();
			string error = bspatch.StandardError.ReadToEnd();
			if(string.IsNullOrEmpty(error))
			{
				Debug.WriteLine("ERROR: " + error);
				return error;
			}
			string output = bspatch.StandardOutput.ReadToEnd();
			Debug.WriteLine(output);
			return output;
		}

		private void ExtractBsPatch()
		{
			if (!File.Exists("bspatch.exe")) // unload bspatch.exe
			{
				Assembly asm = Assembly.GetExecutingAssembly();
				Stream stream = asm.GetManifestResourceStream(asm.GetName().Name + ".bspatch.exe");
				byte[] buffer = new byte[stream.Length];
				stream.Read(buffer, 0, (int) stream.Length);
				File.WriteAllBytes("bspatch.exe", buffer);
			}
		}
	}

	public class PatchFile
	{
		private FileInfo _file;
		public string FilePath
		{
			get
			{
				return _file.FullName;
			}
		}

		public string FileName
		{
			get
			{
				return _file.Name;
			}
		}

		public PatchFile(FileInfo file)
		{
			_file = file;
		}
	}
}
